/**
 * Created by neal on 11/22/16.
 */

var Config = {
    createUrl: '/api/roles',
    updateUrl: '/api/roles',
    deleteUrl: '/api/roles',
    selectUrl: '/api/roles',
    selectUrlForResources: '/api/resources',
    grantUrlForResources: '/api/resources/grant'
};

$.validator.setDefaults({
    highlight: function (e) {
        $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
    }, success: function (e) {
        e.closest(".form-group").removeClass("has-error").addClass("has-success");
    }, errorElement: "span", errorPlacement: function (e, r) {
        e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
    }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
});
$(document).ready(function () {
    $.jgrid.defaults.styleUI = "Bootstrap";
    $(".i-checks").iCheck({checkboxClass: "icheckbox_square-green", radioClass: "iradio_square-green"});
    $.ajax(
        {
            url: Config.selectUrlForResources,
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var group = extractGroup(data.data);
                data = dataWrapper(data.data, group);
                $("#data_list").jqGrid({
                    datatype: "local",
                    data: data,
                    height: 450,
                    autowidth: true,
                    rowNum: 1000,
                    colNames: ["编号", "组名", "权限"],
                    colModel: [{
                        name: "id",
                        index: "id",
                        editable: false,
                        width: 20,
                        sorttype: "int",
                        search: true
                    }, {
                        name: "name",
                        index: "name",
                        editable: true,
                        width: 40
                    }, {
                        name: "sub",
                        index: "sub",
                        editable: true,
                        width: 200
                    }],
                    pager: "#pager_data_list",
                    viewrecords: true,
                    hidegrid: false,
                    gridComplete: function () {
                    }
                });
                jQuery("#data_list").jqGrid('navGrid', '#pager_data_list', {add: false, edit: false, del: false});
                $(window).bind("resize", function () {
                    var width = $(".jqGrid_wrapper").width();
                    $("#data_list").setGridWidth(width);
                });

                renderCheckBoxForChecked();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error(errorThrown);
            }
        });

    //save role
    $('#submitForSave').click(function () {
        $("#ajaxform").validate();
        if ($('#ajaxform').valid()) {
            var postData = $('#ajaxform').serializeArray();
            $.ajax(
                {
                    url: Config.createUrl,
                    type: "POST",
                    data: postData,
                    dataType: "json",
                    success: function (data, textStatus, jqXHR) {
                        toastr.success(data.msg, data.title);
                        if (data && data.type == 'SUCCESS'){
                            getAllRoles();
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        toastr.error(errorThrown, textStatus);
                    }
                });
        }
        return false;
    });

    getAllRoles();

    //grant
    $('#submitForSaveResource').click(function () {
        var checked = $('input[type=checkbox]:checked');
        var roleId = $('input[type=radio]:checked');
        if(!checked || !roleId || checked.length == 0 || roleId.length == 0){
            toastr.error("请选择角色和对应的权限");
            return;
        }
        var postData = {"roleId": $(roleId).val(), "mids": menuIdsWrapper(checked) };
        $.ajax(
        {
            url: Config.grantUrlForResources,
            type: "GET",
            data: postData,
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                toastr.success(data.msg, data.title);
                if (data && data.type == 'SUCCESS'){}
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    });
    //grant clear all permission
    $('#submitForClearResource').click(function () {
        var roleId = $('input[type=radio]:checked');
        if(!roleId || roleId.length == 0){
            toastr.error("请选择角色");
            return;
        }
        var postData = {"roleId": $(roleId).val(), "mids": -1 };
        $.ajax(
        {
            url: Config.grantUrlForResources,
            type: "GET",
            data: postData,
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                toastr.success(data.msg, data.title);
                if (data && data.type == 'SUCCESS'){}
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    });

});

function extractGroup(data) {
    var mydata = [];
    for (var i = 0; i < $(data).size(); i++) {
        if (data[i].pid == 0 && !checkExists(data[i], mydata)) {
            mydata.push(data[i]);
        }
    }
    return mydata;
}

function checkExists(data, array) {
    for (var i = 0; i < $(array).size(); i++) {
        if (data.id == array[i].id) {
            return true;
        }
    }
    return false;
}

function dataWrapper(data, group) {
    for (var i = 0; i < group.length; i++) {
        group[i].name = '<label class="i-checks"><input pid="'+group[i].id+'" class="singleresource" id="singleresource' + group[i].id + '" type="checkbox" value="' + group[i].id + '">' + group[i].name + '</label>';
        var sub = [];
        for (var j = 0; j < data.length; j++) {
            if (group[i].id == data[j].pid) {
                sub.push('<label class="i-checks" style="padding-right: 5px; float: left;"><input class="singleresource" id="singleresource' + data[j].id + '" type="checkbox" value="' + data[j].id + '">' + data[j].name + '</label>');
            }
        }
        group[i].sub = sub.join('');
    }
    return group;
}

function getAllRoles() {

    $.ajax(
        {
            url: Config.createUrl,
            type: "GET",
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                if (data && data.type == 'SUCCESS') {
                    rolesWrapper(data.data);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
}
//Grant
function singleRole() {
    $('label.singlerole').click(function () {
        $.ajax(
        {
            url: Config.selectUrlForResources+'/'+$("input", this).val(),
            type: "GET",
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                if (data && data.type == 'SUCCESS'){
                    renderCheckBox(data.data);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    });
}
//checked
function renderCheckBoxForChecked() {
    $('input.singleresource').click(function () {
        //clean all
        if($(this).attr("pid")){
            $("input.singleresource",$(this).parent().parent().parent()).prop("checked", $(this).prop("checked"));
        }
    });
}
function rolesWrapper(data) {
    var sub = [];
    for (var i = 0; i < data.length; i++) {
        sub.push('<label class="singlerole" ><input type="radio" value="' + data[i].id + '" name="roles"><i></i>' + data[i].name + '</label>');
    }
    $("#allroles").html(sub.join(''));
    // $(".i-checks").iCheck({checkboxClass: "icheckbox_square-green", radioClass: "iradio_square-green"});
    singleRole();
}
function renderCheckBox(data) {
    //clean all
    $("input.singleresource").prop("checked", false);
    //set checked
    if(!data || !data.length) return;

    for (var i = 0; i < data.length; i++) {
        $("#singleresource"+data[i].id).prop("checked", true);
    }
}
function menuIdsWrapper(data) {
    var temp = [];
    for (var i = 0; i < data.length; i++) {
        temp.push($(data[i]).val());
    }
    return temp.join(',');
}

//hello :)~